package gin

import (
	"blockchains-aio/docker"
	"blockchains-aio/gin/listeners"
	"blockchains-aio/gin/misc"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"strings"
)

func Run(port int) error {
	r := gin.Default()

	r.Any("/docker-api-stream/*path", priorTo, func(context *gin.Context) {
		uri := context.Request.RequestURI
		query := ""
		if strings.Contains(uri, "?") {
			index := strings.Index(uri, "?")
			query = uri[index+1:]
		}
		context.GetHeader("PROXY")

		//ri, err := GetRequestInfo("/docker-api", context)
		ri, err := misc.GetRequestInfo(context.Param("path"), context)

		if err != nil {
			log.Fatalf("%v", err)
			return
		}

		if strings.Index(ri.Host, "unix") == 0 {
			if err := docker.WithHttpReverseUnixSocketProxy("/var/run/docker.sock", ri.Host, "http", ri.Path, query, context); err != nil {
				log.Printf("Proxy error : %v", err)
				context.JSON(400, fmt.Sprintf("%v", err))
			} else {
				log.Printf("Successfull proxy over : %v", context.Request.RequestURI)
				return
			}

		}

	}, post)

	r.Any("/docker-api/*path", priorTo, func(context *gin.Context) {
		uri := context.Request.RequestURI
		query := ""
		if strings.Contains(uri, "?") {
			index := strings.Index(uri, "?")
			query = uri[index+1:]
		}
		context.GetHeader("PROXY")

		//ri, err := GetRequestInfo("/docker-api", context)
		ri, err := misc.GetRequestInfo(context.Param("path"), context)

		if err != nil {
			log.Fatalf("%v", err)
			return
		}

		if strings.Index(ri.Host, "unix") == 0 {
			if err := docker.UnixSocketProxy("/var/run/docker.sock", ri.Host, "http", ri.Path, query, context); err != nil {
				log.Printf("Proxy error : %v", err)
				context.JSON(400, fmt.Sprintf("%v", err))
			} else {
				log.Printf("Successfull proxy over : %v", context.Request.RequestURI)
				return
			}

		}

	}, post)

	listeners.RegisterReposRestful(r)
	listeners.RegisterUsage(r)
	listeners.RegisterStack(r)
	listeners.RegisterImage(r)
	listeners.RegisterContract(r)
	listeners.RegisterWallet(r)
	listeners.RegisterPort(r)
	listeners.RegisterStack2(r)
	listeners.RegisterStack2ForPos(r)
	listeners.RegisterSwarm(r)
	listeners.RegisterSlogan(r)
	listeners.RegisterExplorer(r)
	listeners.RegisterSM234(r)

	listeners.RegisterWebSocket(r)
	listeners.RegisterGenesis(r)
	listeners.RegisterStack3(r)
	listeners.RegisterStackCluster(r)

	listeners.RegisterMsp(r)
	listeners.RegisterChainCodeInvocation(r)

	listeners.RegisterEthRpc(r)

	listeners.RegisterMetrics(r)
	listeners.RegisterContractAccount(r)
	listeners.RegisterNs3(r)

	err := r.Run(fmt.Sprintf(":%d", port))
	if err != nil {
		return fmt.Errorf("port conflict: %w", err)
	}

	return nil
}
